package com.itheima.controller;

import com.itheima.pojo.KsClass;
import com.itheima.pojo.LoginDto;
import com.itheima.pojo.User;
import com.itheima.service.LoginService;
import com.itheima.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

/**
 * @author 28066
 * @version 1.0
 * @description: TODO
 * @date 2022/11/11 15:22
 */
@RestController
@RequestMapping("/v1/login")
public class LoginController {
    @Autowired
    private LoginService loginService;

    @GetMapping("/{mobile}")
    public Result findByMobile(@PathVariable("mobile") String mobile) {

        if (loginService.findByMobile(mobile) != null && loginService.findByMobile(mobile).getRoleId() == 1) {
            List<KsClass> allClass = loginService.findAllClass();
            return new Result(0, "操作成功", allClass);
        } else if (loginService.findByMobile(mobile) != null && loginService.findByMobile(mobile).getRoleId() != 1) {
            ArrayList<KsClass> list = new ArrayList<>();
            Integer classId = loginService.findClassId(mobile);
            KsClass aClass = loginService.findClass(classId);
            list.add(aClass);
            return new Result(0, "操作成功", list);
        }
        return new Result(1, "操作失败");
    }

    @PostMapping("/in")
    public Result userLogin(@RequestBody LoginDto loginDto, HttpSession session){
        session.removeAttribute("LoginDto");
        session.removeAttribute("User");
        String mobile=loginDto.getName();
        String password=loginDto.getPassword();
        User user=loginService.loginByMobileAndPassword(mobile,password);

        session.setAttribute("User",user);

        if(user!=null){
            session.setAttribute("LoginDto",loginDto);
            return new Result(0, "操作成功", user);
        }
        return new Result(1, "操作失败");
    }
}
